<template>
  <!-- 搜索框 -->
  <div class="head-container">
    <el-input
      v-model="deptName"
      clearable
      placeholder="请输入部门名称"
      class="mb-20px"
    >
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>

  <!-- 树形控件 -->
  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="deptList"
      node-key="id"
      :props="defaultProps"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      default-expand-all
      highlight-current
      @node-click="handleNodeClick"
    >
      <template #default="{ data }">
        <div class="tree-node-content">
          <span>{{ data.name }}</span>
          <el-popover
            :visible="data.showMenu"
            trigger="click"
            popper-class="custom-popover"
            @show="handlePopoverShow(data)"
            @hide="handlePopoverHide(data)"
          >
            <template #reference>
              <el-icon class="more-icon" @click.stop="handleMoreClick(data)">
                <More />
              </el-icon>
            </template>
            <el-menu class="custom-menu">
              <el-menu-item @click="handleAction('addChild', data)">
                <div class="menu-item-content">添加目录</div>
              </el-menu-item>
              <el-menu-item @click="handleAction('edit', data)">
                <div class="menu-item-content">修改</div>
              </el-menu-item>
              <el-menu-item @click="handleAction('delete', data)">
                <div class="menu-item-content">删除</div>
              </el-menu-item>
            </el-menu>
          </el-popover>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { ElTree } from 'element-plus'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import { More } from '@element-plus/icons-vue'

defineOptions({ name: 'SystemUserDeptTree' })

const deptName = ref('')
const deptList = ref<Tree[]>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const lastClickedNode = ref<Tree | null>(null)

// 获取部门树数据
const getTree = async () => {
  const res = await DeptApi.getSimpleDeptList()
  deptList.value = handleTree(res).map(item => ({ ...item, showMenu: false }))
}

// 过滤节点
const filterNode = (name: string, data: Tree) => !name || data.name.includes(name)

// 节点点击
const handleNodeClick = (row: any) => emits('node-click', row)
const emits = defineEmits(['node-click'])

// 监听搜索关键字
watch(deptName, val => treeRef.value?.filter(val))

// 菜单显示/隐藏处理
const handlePopoverShow = (data: Tree) => {
  document.addEventListener('click', e => handleClickOutside(e, data))
}

const handlePopoverHide = (data: Tree) => {
  document.removeEventListener('click', e => handleClickOutside(e, data))
}

const handleMoreClick = (data: Tree) => {
  if (lastClickedNode.value && lastClickedNode.value !== data) {
    lastClickedNode.value.showMenu = false
  }
  data.showMenu = !data.showMenu
  lastClickedNode.value = data
}

const handleAction = (actionType: string, data: Tree) => {
  console.log(`执行 ${actionType} 操作:`, data)
  data.showMenu = false
}

const handleClickOutside = (event: MouseEvent, data: Tree) => {
  const target = event.target as HTMLElement
  if (!target.closest('.el-popover') && !target.closest('.el-menu')) {
    data.showMenu = false
    document.removeEventListener('click', e => handleClickOutside(e, data))
  }
}

onMounted(() => getTree())
onUnmounted(() => document.removeEventListener('click', e => handleClickOutside(e, null as any)))

interface Tree {
  id: number | string
  name: string
  children?: Tree[]
  showMenu?: boolean
}
</script>

<style>
.el-popper.custom-popover {
  padding: 4px !important;
  width: auto !important;
  min-width: 0 !important;
}

.custom-menu {
  border: none !important;
}

.custom-menu .el-menu-item {
  height: 32px !important;
  line-height: 32px !important;
  padding: 0 8px !important;
  min-width: 0 !important;
  width: auto !important;
}

.custom-menu .menu-item-content {
  font-size: 14px;
  width: 60px;
  text-align: left;
  white-space: nowrap;
}

.el-menu--popup {
  padding: 0 !important;
  min-width: 0 !important;
}
</style>

<style scoped>
.tree-node-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.tree-node-content .more-icon {
  opacity: 0;
  color: #999;
  font-size: 16px;
  margin-right: 20px;
}

.tree-node-content:hover .more-icon {
  opacity: 1;
}
</style>
